﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace QuanLyKTX
{
    using DAL;
    using Telerik.WinControls;
    using Telerik.WinControls.UI;
    using Utilities;

    public partial class frm_Contracts : Telerik.WinControls.UI.RadForm
    {
        public string MaSinhVien { get; set; }
        public int ID { get; set; }
        public string Truong { get; set; }
        public Guid MaHopDong { get; set; }
        #region Private Methods

        RadContextMenu contextMenu;
        bool update = false;

        private void ResetForm()
        {
            radTextBox_HoTen.Clear();
            radTextBox_ThuongTru.Clear();
            radTextBox_SoCMND.Clear();
            radTextBox_MaSV.Focus();
            radTextBox_MaSV.SelectAll();
        }

        private void SetDefaultLoadForm()
        {
            Truong = "VLU";
            radDateTimePicker_NgayLap.Value = DateTime.Now;
            radDateTimePicker_NgayLap.MaxDate = DateTime.Now;
            radDateTimePicker_NgayHieuLuc.Value = DateTime.Now;
            radMaskedEditBox_KyHan.Value = 5;
            radDateTimePicker_NgayKetThuc.Value = radDateTimePicker_NgayHieuLuc.Value.AddMonths(Convert.ToInt32(radMaskedEditBox_KyHan.Value));

            using (var db = new QuanLyKTXDataContext())
            {
                var result = (from p in db.tbl_CauHinhApDungPhis
                              where p.MaLoaiHD == (radRadioButton_CaNhan.IsChecked ? Convert.ToByte(1) : Convert.ToByte(2)) && p.KichHoat == true
                              select p).FirstOrDefault();
                if (result != null)
                {
                    radMaskedEditBox_PhiBanDau.Value = result.PhiBanDauVL;
                }
            }
        }

        private void BindGridView(int id)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var results = from p in db.tbl_HopDongs
                              join q in db.tbl_SinhViens on p.ID equals q.ID
                              where q.ID == id
                              select new
                              {
                                  p.MaHopDong,
                                  p.ID,
                                  SoHD = string.Format("{0}/{1}", p.SoHopDong, p.HauTo),
                                  q.MaSinhVien,
                                  HoTen = String.Format("{0} {1}", q.Ho, q.Ten),
                                  p.NgayBatDauHD,
                                  p.NgayKetThucHD
                              };

                radGridView_HopDong.DataSource = results;
                radGridView_HopDong.AutoGenerateColumns = false;
            }
        }

        private void InsHopDong(int id, int kyHanHD, DateTime ngayHieuLuc, Decimal phiBanDau)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                if (db.tbl_HopDongs.Where(p => p.ID == id && p.NgayThanhLyHD == null).Count() < 1)
                {
                    int soHopDong = 0;
                    var results = from p in db.tbl_HopDongs
                                  select p;

                    if (results.Count() > 0)
                    {
                        soHopDong = results.Max(p => p.SoHopDong);
                    }

                    // Lấy phí áp dụng cho loại hợp đồng khác nhau
                    var caNhan = (from p in db.tbl_CauHinhApDungPhis
                                  where p.MaLoaiHD == 1 && p.KichHoat == true
                                  select p).FirstOrDefault();
                    var baoPhong = (from p in db.tbl_CauHinhApDungPhis
                                    where p.MaLoaiHD == 2 && p.KichHoat == true
                                    select p).FirstOrDefault();

                    // thêm vào table tbl_HopDong
                    tbl_HopDong hopDong = new tbl_HopDong
                    {
                        MaHopDong = Guid.NewGuid(),
                        SoHopDong = soHopDong + 1,
                        HauTo = "VL/KTX/" + ngayHieuLuc.Year,
                        ID = id,
                        NgayBatDauHD = ngayHieuLuc,
                        NgayKetThucHD = ngayHieuLuc.AddMonths(kyHanHD),
                        NgayKyHD = radDateTimePicker_NgayLap.Value,
                        LoaiHopDong = radRadioButton_CaNhan.IsChecked ? Convert.ToByte(1) : Convert.ToByte(2),
                        PhiBanDau = radRadioButton_CaNhan.IsChecked ? caNhan.PhiBanDau : baoPhong.PhiBanDau,
                        PhiBanDauVL = radRadioButton_CaNhan.IsChecked ? caNhan.PhiBanDauVL : baoPhong.PhiBanDauVL,
                        TienPhong = radRadioButton_CaNhan.IsChecked ? caNhan.TienPhong : baoPhong.TienPhong,
                        TienPhongVL = radRadioButton_CaNhan.IsChecked ? caNhan.TienPhongVL : baoPhong.TienPhongVL,
                        MienGiam = Convert.ToByte(33),
                        KyHan = radMaskedEditBox_KyHan.Value.ToString() == string.Empty ? Convert.ToByte(0) : Convert.ToByte(radMaskedEditBox_KyHan.Value.ToString())
                    };
                    db.tbl_HopDongs.InsertOnSubmit(hopDong);
                    db.SubmitChanges();

                    // Thêm vào table tbl_HoaDonPhong
                    for (int i = 1; i <= hopDong.KyHan; i++)
                    {
                        tbl_HoaDonPhong hoaDonPhong = new tbl_HoaDonPhong { MaHoaDon = Guid.NewGuid(), MaHopDong = hopDong.MaHopDong };

                        var result = from p in db.tbl_SinhViens
                                     where p.MaTruong == "VLU" && p.ID == id
                                     select p;

                        if (result.Count() > 0)
                            hoaDonPhong.SoTien = hopDong.TienPhongVL;
                        else
                            hoaDonPhong.SoTien = hopDong.TienPhong;

                        hoaDonPhong.NgayThanhToan = ngayHieuLuc.AddMonths(i);
                        hoaDonPhong.KyThang = Convert.ToByte(ngayHieuLuc.AddMonths(i).Month);
                        hoaDonPhong.Nam = ngayHieuLuc.AddMonths(i).Year.ToString();

                        db.tbl_HoaDonPhongs.InsertOnSubmit(hoaDonPhong);
                        db.SubmitChanges();
                    }


                    BindGridView(id);
                    ResetForm();
                }
                else
                {
                    MessageBox.Show("Sinh viên trên chưa thanh lý hợp đồng hiện tại. Không thể lập hợp đồng mới.");
                }
            }
        }

        private void UpdHopDong(Guid maHopDong, DateTime ngayLapHD, DateTime ngayHieuLuc, DateTime ngayKetThuc, Decimal phiBanDau)
        {
            try
            {
                using (var db = new QuanLyKTXDataContext())
                {
                    var caNhan = (from p in db.tbl_CauHinhApDungPhis
                                  where p.MaLoaiHD == 1 && p.KichHoat == true
                                  select p).FirstOrDefault();
                    var baoPhong = (from p in db.tbl_CauHinhApDungPhis
                                    where p.MaLoaiHD == 2 && p.KichHoat == true
                                    select p).FirstOrDefault();

                    var hopDong = (from p in db.tbl_HopDongs
                                   where p.MaHopDong == maHopDong
                                   select p).Single();
                    hopDong.NgayKyHD = ngayLapHD;
                    hopDong.NgayBatDauHD = ngayHieuLuc;
                    hopDong.KyHan = radMaskedEditBox_KyHan.Value.ToString() == string.Empty ? Convert.ToByte(0) : Convert.ToByte(radMaskedEditBox_KyHan.Value.ToString());
                    hopDong.NgayKetThucHD = ngayKetThuc;
                    hopDong.LoaiHopDong = radRadioButton_CaNhan.IsChecked ? Convert.ToByte(1) : Convert.ToByte(2);
                    hopDong.PhiBanDau = radRadioButton_CaNhan.IsChecked ? caNhan.PhiBanDau : baoPhong.PhiBanDau;
                    hopDong.PhiBanDauVL = radRadioButton_CaNhan.IsChecked ? caNhan.PhiBanDauVL : baoPhong.PhiBanDauVL;
                    hopDong.TienPhong = radRadioButton_CaNhan.IsChecked ? caNhan.TienPhong : baoPhong.TienPhong;
                    hopDong.TienPhongVL = radRadioButton_CaNhan.IsChecked ? caNhan.TienPhongVL : baoPhong.TienPhongVL;

                    db.SubmitChanges();
                    update = false;

                    BindGridView(hopDong.ID);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BindKhoa()
        {
            using (var db = new QuanLyKTXDataContext())
            {
                //radDropDownList_Khoa.DataSource = db.tbl_Khoas.Where(p => ((db.tbl_Lops.Select(q => q.MaKhoa).Contains(p.MaKhoa)) && (p.IsVocation == (Boolean?)false))).ToList();
                //radDropDownList_Khoa.ValueMember = "MaKhoa";
                //radDropDownList_Khoa.DisplayMember = "TenKhoa";
            }
        }

        private void BindLop(string maKhoa)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                //radDropDownList_Lop.DataSource = db.tbl_Lops.Where(p => p.MaKhoa == maKhoa).ToList();
                //radDropDownList_Lop.ValueMember = "MaLop";
                //radDropDownList_Lop.DisplayMember = "MaLop";
            }
        }

        private bool BindThongTinSinhVien(int id)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var result = (from p in db.tbl_SinhViens
                              where p.ID == id
                              select new
                              {
                                  p.MaSinhVien,
                                  p.MaTruong,
                                  TenTruong = (from q in db.tbl_Truongs where q.MaTruong == p.MaTruong select q.TenTruong).FirstOrDefault(),
                                  p.MaLop,
                                  p.Ho,
                                  p.Ten,
                                  p.NgaySinh,
                                  GioiTinh = p.GioiTinh.Value ? "Nam" : "Nữ",
                                  p.SoCMND,
                                  p.NoiCap,
                                  p.NgayCap,
                                  p.DiaChi,
                                  p.SoDienThoai,
                                  p.Email,
                                  p.KhoaTaiKhoan
                              }).FirstOrDefault();

                if (result != null)
                {
                    Truong = result.MaTruong;
                    radTextBox_MaSV.Text = result.MaSinhVien;
                    radTextBox_HoTen.Text = String.Format("{0} {1}", result.Ho, result.Ten);
                    radTextBox_Truong.Text = result.TenTruong;
                    radTextBox_SoCMND.Text = result.SoCMND;
                    radTextBox_ThuongTru.Text = result.DiaChi;

                    var phiBanDau = (from r in db.tbl_CauHinhApDungPhis
                                     where r.MaLoaiHD == (radRadioButton_CaNhan.IsChecked ? Convert.ToByte(1) : Convert.ToByte(2)) && r.KichHoat == true
                                     select r).FirstOrDefault();

                    if (phiBanDau != null)
                    {
                        if (result.MaTruong == "VLU")
                            radMaskedEditBox_PhiBanDau.Value = phiBanDau.PhiBanDauVL;
                        else
                            radMaskedEditBox_PhiBanDau.Value = phiBanDau.PhiBanDau;
                    }

                    return true;
                }
                else
                {
                    MessageBox.Show("Không tìm thấy bất kỳ thông tin nào có Mã SV này.");
                    return false;
                }
            }
        }

        private void InitContextMenu()
        {
            contextMenu = new RadContextMenu();
            RadMenuItem menuItemPrint = new RadMenuItem("Xem và in");
            menuItemPrint.Click += new EventHandler(menuItemPrint_Click);
            RadMenuItem menuItemSua = new RadMenuItem("Sửa");
            menuItemSua.Click += new EventHandler(menuItemSua_Click);

            contextMenu.Items.Add(menuItemPrint);
            contextMenu.Items.Add(menuItemSua);

        }

        #endregion

        #region Event Methods

        void menuItemSua_Click(object sender, EventArgs e)
        {
            Guid maHopDong = new Guid(radGridView_HopDong.CurrentRow.Cells[0].Value.ToString());
            int id = Convert.ToInt32(radGridView_HopDong.CurrentRow.Cells[1].Value);
            MaHopDong = maHopDong;
            using (var db = new QuanLyKTXDataContext())
            {
                var hopDong = (from p in db.tbl_HopDongs
                               where p.MaHopDong == maHopDong
                               select p).FirstOrDefault();

                radDateTimePicker_NgayHieuLuc.Value = hopDong.NgayBatDauHD.Value.Date;
                radDateTimePicker_NgayKetThuc.Value = hopDong.NgayKetThucHD.Value.Date;
                radDateTimePicker_NgayLap.Value = hopDong.NgayKyHD.Value.Date;
                radMaskedEditBox_KyHan.Value = hopDong.KyHan;
                if (hopDong.LoaiHopDong.Value == 1)
                {
                    radRadioButton_CaNhan.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On;
                }
                else
                {
                    radRadioButton_DaiDienPhong.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On;
                }

                BindThongTinSinhVien(id);
                update = true;
            }
        }

        private void radRadioButton_DaiDienPhong_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var phiBanDau = (from r in db.tbl_CauHinhApDungPhis
                                 where r.MaLoaiHD == Convert.ToByte(2) && r.KichHoat == true
                                 select r).FirstOrDefault();
                if (phiBanDau != null)
                {
                    if (Truong.Equals("VLU"))
                        radMaskedEditBox_PhiBanDau.Value = phiBanDau.PhiBanDauVL;
                    else radMaskedEditBox_PhiBanDau.Value = phiBanDau.PhiBanDau;
                }
            }
        }

        private void radRadioButton_CaNhan_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var phiBanDau = (from r in db.tbl_CauHinhApDungPhis
                                 where r.MaLoaiHD == Convert.ToByte(1) && r.KichHoat == true
                                 select r).FirstOrDefault();
                if (phiBanDau != null)
                {
                    if (Truong.Equals("VLU"))
                        radMaskedEditBox_PhiBanDau.Value = phiBanDau.PhiBanDauVL;
                    else radMaskedEditBox_PhiBanDau.Value = phiBanDau.PhiBanDau;
                }
            }
        }

        private void radMaskedEditBox_KyHan_Leave(object sender, EventArgs e)
        {
            int kyHan = radMaskedEditBox_KyHan.Value.ToString() == String.Empty ? 0 : Convert.ToInt32(radMaskedEditBox_KyHan.Value);
            radDateTimePicker_NgayKetThuc.Value = radDateTimePicker_NgayHieuLuc.Value.AddMonths(kyHan);
        }

        private void radDateTimePicker_NgayHieuLuc_ValueChanged(object sender, EventArgs e)
        {
            int kyHan = radMaskedEditBox_KyHan.Value.ToString() == String.Empty ? 0 : Convert.ToInt32(radMaskedEditBox_KyHan.Value);
            radDateTimePicker_NgayKetThuc.Value = radDateTimePicker_NgayHieuLuc.Value.AddMonths(kyHan);
        }

        private void radButton_KTMaSV_Click(object sender, EventArgs e)
        {
            string maSinhVien = radTextBox_MaSV.Text.Trim();
            string soCMND = radTextBox_SoCMND.Text.Trim();
            if (!String.IsNullOrEmpty(maSinhVien))
            {
                using (var db = new QuanLyKTXDataContext())
                {
                    var result = (from p in db.tbl_SinhViens
                                  where p.MaSinhVien == maSinhVien
                                  select p).FirstOrDefault();
                    if (result != null)
                    {
                        ID = result.ID;
                        MaSinhVien = result.MaSinhVien;
                        BindThongTinSinhVien(ID);
                        BindGridView(ID);
                    }
                    else
                    {
                        ID = 0;
                        MessageBox.Show("Không tìm thấy bất kỳ thông tin nào có Mã SV này.");
                        ResetForm();
                    }
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(soCMND))
                {
                    using (var db = new QuanLyKTXDataContext())
                    {
                        var result = (from p in db.tbl_SinhViens
                                      where p.SoCMND == soCMND
                                      select p).FirstOrDefault();
                        if (result != null)
                        {
                            ID = result.ID;
                            MaSinhVien = result.MaSinhVien;
                            BindThongTinSinhVien(ID);
                            BindGridView(ID);
                        }
                        else
                        {
                            ID = 0;
                            MessageBox.Show("Không tìm thấy bất kỳ thông tin nào có Số CMND này.");
                            ResetForm();
                        }
                    }
                }
                else
                {
                    if (ID > 0)
                    {
                        BindThongTinSinhVien(ID);
                        BindGridView(ID);
                    }
                }
            }

            //BindGridView(radTextBox_MaSV.Text.Trim());
        }

        private void frm_Contracts_Activated(object sender, EventArgs e)
        {
            if (radTextBox_MaSV.Text.Length > 0)
            {
                BindThongTinSinhVien(ID);
            }
        }

        void menuItemPrint_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(radGridView_HopDong.CurrentRow.Cells[1].Value);
            Guid maHopDong = new Guid(radGridView_HopDong.CurrentRow.Cells[0].Value.ToString());

            using (var db = new QuanLyKTXDataContext())
            {
                var sinhVienInfo = (from p in db.tbl_SinhViens
                                    where p.ID == id
                                    select p).FirstOrDefault();

                var hopDongInfo = (from p in db.tbl_HopDongs
                                   where p.MaHopDong == maHopDong
                                   select p).FirstOrDefault();

                using (frm_ReportContractViewer contractViewer = new frm_ReportContractViewer(sinhVienInfo, hopDongInfo))
                {
                    contractViewer.ShowDialog();
                }
            }
        }

        private void radGridView_HopDong_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
        {
            if (!radGridView_HopDong.CurrentRow.IsSystem)
            {
                e.ContextMenu = contextMenu.DropDown;
            }
        }

        private void radButton_XemBanIn_Click(object sender, EventArgs e)
        {
            tbl_SinhVien sinhVienInfo = new tbl_SinhVien { MaSinhVien = radTextBox_MaSV.Text.Trim(), Ho = radTextBox_HoTen.Text.Trim() };

            tbl_HopDong hopDongInfo = new tbl_HopDong { MaHopDong = Guid.NewGuid(), /*hopDongInfo.MaSinhVien = radTextBox_MaSV.Text.Trim();*/NgayBatDauHD = radDateTimePicker_NgayHieuLuc.Value, NgayKetThucHD = radDateTimePicker_NgayHieuLuc.Value.AddMonths(Convert.ToInt32(radMaskedEditBox_KyHan.Value)) };

            using (frm_ReportContractViewer reportViewer = new frm_ReportContractViewer(sinhVienInfo, hopDongInfo))
            {
                reportViewer.ShowDialog();
            }
        }

        private void radDropDownList_Khoa_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            //BindLop(Convert.ToString(radDropDownList_Khoa.SelectedValue));
        }

        private void radButton_Luu_Click(object sender, EventArgs e)
        {
            //Regex reg = new Regex(@"^(\d{1,6})");

            //if (radTextBox_MaSV.Text.Trim().Length > 0)
            //{
            int kyHan = radMaskedEditBox_KyHan.Value.ToString() == String.Empty ? 0 : Convert.ToInt32(radMaskedEditBox_KyHan.Value);
            decimal phiBanDau = radMaskedEditBox_PhiBanDau.Value.ToString() == String.Empty ? 0 : Convert.ToDecimal(radMaskedEditBox_PhiBanDau.Value);
            if (!update)
            {
                if (BindThongTinSinhVien(ID))
                {

                    InsHopDong(ID, kyHan, radDateTimePicker_NgayHieuLuc.Value, phiBanDau);
                }
            }
            else
            {
                UpdHopDong(MaHopDong, radDateTimePicker_NgayLap.Value, radDateTimePicker_NgayHieuLuc.Value, radDateTimePicker_NgayKetThuc.Value, phiBanDau);
            }


            //}
            //else
            //{
            //    MessageBox.Show("Cần nhập mã Sinh viên");
            //    radTextBox_MaSV.Focus();
            //}


        }

        private void radButton_Xoa_Click(object sender, EventArgs e)
        {
            ResetForm();
        }

        public frm_Contracts()
        {
            InitializeComponent();
            ID = 0;
        }

        public frm_Contracts(int id)
        {
            InitializeComponent();
            ID = id;
        }

        private void radButton_Thoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void frm_Contracts_Load(object sender, EventArgs e)
        {
            SetDefaultLoadForm();
            ResetForm();
            if (ID > 0)
            {
                BindThongTinSinhVien(ID);
                BindGridView(ID);
            }
            InitContextMenu();
        }

        #endregion
    }
}
